/*
	Copyright 2009 Omer Saatcioglu
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.

	$Author$
	$Revision$
	$LastChangedDate$
   
 */

package com.saatcioglu.android.guessthenumber;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class GfxGuesstheNumber extends ListActivity implements OnClickListener{

	static final protected int NEWGAME_ID = Menu.FIRST;
	static final protected int SHOWMETHENUMBER_ID = Menu.FIRST + 1;
	static final protected int ABOUT_ID = Menu.FIRST + 3;
	static final protected int EXIT_ID = Menu.FIRST + 4;
	
/*	
	static final private String GS_GAMESTARTED = "isGameStarted";
	static final private String GS_EDITORTEXT = "mEditorText";
	static final private String GS_STRINGS = "mStrings_";
	static final private String GS_COUNTER = "intCounter";
	static final private String GS_DIGITSPRESSED = "theDigitsPressed";
	static final private String GS_PREVBUTTONS = "arrintPrevButtons_";
	static final private String GS_ELAPSEDTIME = "lngElapsedTime_";
	static final private String GS_BUTTONENABLED = "arrisButtonEnabled_";
	static final private String GS_BUTTONSTATES = "arrintButtonStates";
	static final private String GS_SECRETNUMBER = "intSecretNumber";
*/
	static private GfxGuesstheNumber gfxGuesstheNumber = null;

	private ArrayList<String> mStrings = new ArrayList<String>();
	private ArrayAdapter<String> mAdapter;
	private Vibrator vibrator;
	private TextView txtviewCount;
	private MyChronometer chronMain;
	protected EditText edtNewNumber;
	private int intCounter;
	protected NumberConsole numberConsole;

	static public GfxGuesstheNumber getInstance() {
		if (gfxGuesstheNumber == null) {
			Log.d("GfxGuesstheNumber::getInstance", "gfxGuesstheNumber = null");
		}
		return gfxGuesstheNumber;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		preparePreference();
		super.onCreate(savedInstanceState);
		this.setTitle(getString(R.string.app_name)
				+ getString(R.string.abbr_version)
				+ getString(R.string.app_version));
		setContentView(R.layout.guessthenumber);
		SetDisplayElements();
		StartaNewGame();
//		if(savedInstanceState != null){
//			resumetheGameBundle(savedInstanceState);
//		}
//		else{
			CtrlMaintanence.getInstance().resumetheGame();
//		}
		UpdateDisplayElements();
		gfxGuesstheNumber = this;
	}

	@Override
	protected void onPause() {
		chronMain.pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		if(SMBGuesstheNumber.isGameStarted)
		{
			chronMain.resume();
		}
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (SMBGuesstheNumber.isGameStarted) {
			savetheGame();
		}
		CtrlMaintanence.getInstance().savetheGame();
		
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, NEWGAME_ID, NEWGAME_ID, R.string.newgame);
		menu.add(0, SHOWMETHENUMBER_ID, SHOWMETHENUMBER_ID, R.string.showmethenumber);
		menu.add(0, EXIT_ID, EXIT_ID, R.string.exit);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case NEWGAME_ID:
			SMBGuesstheNumber.isGameStarted = false;
			StartaNewGame();
			return true;
		case SHOWMETHENUMBER_ID:
			SMBGuesstheNumber.isGameStarted = false;
			ShowmetheNumber();
			return true;
		case ABOUT_ID:
			showDialog(R.id.display_hints);
			return true;
		case EXIT_ID:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void onClick(View v) {
		switch (((Button) v).getId()) {
		case R.id.enter:
			entertheNumber();
			break;
		case R.id.clear:
			cleartheNumber();
			break;
		case R.id.number_zero:
		case R.id.number_one:
		case R.id.number_two:
		case R.id.number_three:
		case R.id.number_four:
		case R.id.number_five:
		case R.id.number_six:
		case R.id.number_seven:
		case R.id.number_eight:
		case R.id.number_nine:
			addtotheNumber(edtNewNumber, (Button) v);
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case R.id.display_hints:
			return new AlertDialog.Builder(this).setIcon(R.drawable.droid)
					.setTitle(R.string.dialog_hint_title).setMessage(
							R.string.dialog_hint_text).setPositiveButton(
							R.string.OK, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).create();
		}
		return null;
	}

	protected void StartaNewGame() {
		CtrlGuesstheNumber.getInstance().setDigitNumber(SMBGuesstheNumber.nActiveDigits);
		CtrlGuesstheNumber.getInstance().settheSecretNumber();

		numberConsole.reset();
		
		edtNewNumber.setText("");
		mAdapter.clear();
		chronMain.stop();
		chronMain.reset();
		intCounter = 0;
		txtviewCount.setText(getString(R.string.totalshots)
				+ Integer.toString(intCounter));
	}

	protected void ShowmetheNumber() {
		edtNewNumber.setText(Integer.toString(CtrlGuesstheNumber.getInstance().gettheSecretNumber()));
		chronMain.stop();
		numberConsole.disable();
	}

	private void addtotheNumber(EditText theNumber, Button theButtonPressed) {
		theNumber.append(theButtonPressed.getText().toString());
		chronMain.start();
		SMBGuesstheNumber.isGameStarted = true;
		numberConsole.numberSelected(theNumber, theButtonPressed);
	}

	private void cleartheNumber() {

		edtNewNumber.setText(edtNewNumber.getText().toString().substring(0,
				edtNewNumber.getText().toString().length() - 1));
		numberConsole.clearNumber(edtNewNumber);
	}

	protected void entertheNumber() {

		int[] theResult = CtrlGuesstheNumber.getInstance().ProcesstheNumber(
				Integer.parseInt(edtNewNumber.getText().toString()));
		mAdapter.add(getString(R.string.margin) + getString(R.string.plus)
				+ theResult[0] + getString(R.string.minus) + theResult[1]
				+ getString(R.string.gap) + edtNewNumber.getText().toString());
		edtNewNumber.setText("");
		numberConsole.enterNumber();
		intCounter++;
		txtviewCount.setText(getString(R.string.totalshots)
				+ Integer.toString(intCounter));

		if (theResult[0] == SMBGuesstheNumber.nActiveDigits && theResult[1] == 0) {
			gameSucceded();
		} else if (SMBGuesstheNumber.nActiveMaxShots != 0 && intCounter == SMBGuesstheNumber.nActiveMaxShots) {
			gameFailed();
		}
	}

	public void gameFailed() {
		SMBGuesstheNumber.isGameStarted = false;
		CtrlMaintanence.getInstance().savetheGame();
		ShowmetheNumber();
		vibrator.vibrate(100);
		removeDialog(R.id.display_failure);
		showDialog(R.id.display_failure);
	}

	protected void gameSucceded() {
		SMBGuesstheNumber.isGameStarted = false;
		ShowmetheNumber();
		vibrator.vibrate(100);
	}

	private void SetDisplayElements() {

		mAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, mStrings) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				TextView txtView = new TextView(this.getContext());
				txtView.setTextSize(16);
				txtView.setText(this.getItem(position));
				return txtView;
			}
		};

		setListAdapter(mAdapter);
		getListView().setTextFilterEnabled(true);
		edtNewNumber = (EditText) findViewById(R.id.userText);
		txtviewCount = (TextView) findViewById(R.id.TextViewCount);
		chronMain = (MyChronometer) findViewById(R.id.ChronometerStart);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		numberConsole = new NumberConsole(this);
	}

	private void UpdateDisplayElements() {

		if (SMBGuesstheNumber.bShowTotalShots) {
			txtviewCount.setVisibility(View.VISIBLE);
		} else {
			txtviewCount.setVisibility(View.INVISIBLE);
		}

		if (SMBGuesstheNumber.bShowElapsedTime) {
			chronMain.setVisibility(View.VISIBLE);
		} else {
			chronMain.setVisibility(View.INVISIBLE);
		}
		numberConsole.update();
	}

	protected void resumetheGame() {
		edtNewNumber.setText(SMBGuesstheNumber.mEditorText);
		for (String strGuess : SMBGuesstheNumber.mStrings) {
			mAdapter.add(strGuess);
		}
		intCounter = SMBGuesstheNumber.intCounter;
		numberConsole.resume();
		txtviewCount.setText(getString(R.string.totalshots)
				+ Integer.toString(intCounter));
		chronMain.start(SMBGuesstheNumber.lngElapsedTime);
		CtrlGuesstheNumber.getInstance().setDigitNumber(SMBGuesstheNumber.nActiveDigits);
		CtrlGuesstheNumber.getInstance().settheSecretNumber(SMBGuesstheNumber.intSecretNumber);

	}

	protected void savetheGame() {

		SMBGuesstheNumber.mEditorText = edtNewNumber.getText().toString();
		SMBGuesstheNumber.mStrings = mStrings;
		SMBGuesstheNumber.intCounter = intCounter;
		SMBGuesstheNumber.lngElapsedTime = chronMain.getElapsedTime();
		SMBGuesstheNumber.intSecretNumber = CtrlGuesstheNumber.getInstance().gettheSecretNumber();
		numberConsole.saveTheState();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu = numberConsole.createContextMenu(menu, (Button)v);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return (numberConsole.doContextMenu(item) ? true : super.onContextItemSelected(item));
	}

	protected void preparePreference() {
		// virtual method. it is overwritten by the sub classes.		
	}
	
	protected String formatMission(){
		String message = new String();

		message = getString(R.string.text_gen_mission)
		+ getString(R.string.text_gen_number1)
		+ CtrlMaintanence.getInstance().formatShots(SMBGuesstheNumber.nActiveDigits)
		+ getString(R.string.text_gen_number2);
		
		boolean isMaxShotsNonZero = (SMBGuesstheNumber.nActiveMaxShots >0); 
		if(isMaxShotsNonZero){
			message = message 
			+ getString(R.string.text_gen_shots1)
			+ CtrlMaintanence.getInstance().formatShots(SMBGuesstheNumber.nActiveMaxShots)
			+ getString(R.string.text_gen_shots2);
		}
		if(SMBGuesstheNumber.nActiveMaxTime > 0){
			if(isMaxShotsNonZero){
				message = message 
				+ getString(R.string.text_gen_number3);
			}
			message = message 
			+ getString(R.string.text_gen_time1)
			+ CtrlMaintanence.getInstance().formatTime(SMBGuesstheNumber.nActiveMaxTime)
			+ getString(R.string.text_gen_time2);
			if(isMaxShotsNonZero){
				message = message 
				+ getString(R.string.text_gen_number4);
			}
		}
		else{
			if(isMaxShotsNonZero){
				message += _formatMissionTimeMasterShot();
			} else{
				message += _formatMissionTimeandMaxMasterShot();
			}
		}
		return message;
	}
	
	protected String _formatMissionTimeMasterShot(){
		// it will be overwritten by GfxMasterShot only.
		return "";
	}
	protected String _formatMissionTimeandMaxMasterShot(){
		// it will be overwritten by GfxMasterShot only.
		return "";
	}
	
/*	
	public void resumetheGameBundle(Bundle inBundle) {
		int i;

		SMBGuesstheNumber.isGameStarted = inBundle.getBoolean(GS_GAMESTARTED, false);
		if (SMBGuesstheNumber.isGameStarted) {
			SMBGuesstheNumber.mEditorText = inBundle.getString(GS_EDITORTEXT);
			SMBGuesstheNumber.mStrings.clear();
			for (i = 0; inBundle.containsKey(GS_STRINGS + Integer.toString(i)); i++) {
				SMBGuesstheNumber.mStrings.add(inBundle.getString(GS_STRINGS + Integer.toString(i)));
			}
			SMBGuesstheNumber.intCounter = inBundle.getInt(GS_COUNTER, 0);
			SMBGuesstheNumber.theDigitsPressed = inBundle.getInt(GS_DIGITSPRESSED, 0);
			if (SMBGuesstheNumber.arrintPrevButtons == null) {
				SMBGuesstheNumber.arrintPrevButtons = new int[SMBGuesstheNumber.nActiveDigits];
			}
			for (i = 0; i < SMBGuesstheNumber.nActiveDigits && inBundle.containsKey(GS_PREVBUTTONS + Integer.toString(i)); i++) {
				SMBGuesstheNumber.arrintPrevButtons[i] = inBundle.getInt(GS_PREVBUTTONS + Integer.toString(i), 0);
			}
			SMBGuesstheNumber.lngElapsedTime = inBundle.getLong(GS_ELAPSEDTIME, 0);
			for (i = 0; inBundle.containsKey(GS_BUTTONENABLED + Integer.toString(i)); i++) {
				SMBGuesstheNumber.arrisBtnNumberEnabled[i] = inBundle.getBoolean(GS_BUTTONENABLED + Integer.toString(i), true);
			}

			for (i = 0; inBundle.containsKey(GS_BUTTONSTATES + Integer.toString(i)); i++) {
				SMBGuesstheNumber.arrintBtnNumberStates[i] = inBundle.getInt(GS_BUTTONSTATES + Integer.toString(i), 0);
			}
			SMBGuesstheNumber.intSecretNumber = inBundle.getInt(GS_SECRETNUMBER, 0);
		}
	}

	public Bundle savetheGameBundle(Bundle outBundle) {
		if (SMBGuesstheNumber.isGameStarted) {
			int i;
			outBundle.putBoolean(GS_GAMESTARTED, SMBGuesstheNumber.isGameStarted);
			outBundle.putString(GS_EDITORTEXT, SMBGuesstheNumber.mEditorText);
			i = 0;
			for (String tmpString : SMBGuesstheNumber.mStrings) {
				outBundle.putString(GS_STRINGS + Integer.toString(i), tmpString);
				i++;
			}
			outBundle.putInt(GS_COUNTER, SMBGuesstheNumber.intCounter);
			outBundle.putInt(GS_DIGITSPRESSED, SMBGuesstheNumber.theDigitsPressed);
			for (i = 0; i < SMBGuesstheNumber.nActiveDigits; i++) {
				outBundle.putInt(GS_PREVBUTTONS + Integer.toString(i),
						SMBGuesstheNumber.arrintPrevButtons[i]);
			}
			outBundle.putLong(GS_ELAPSEDTIME, SMBGuesstheNumber.lngElapsedTime);
			for (i = 0; i < SMBGuesstheNumber.NBUTTON_ENABLED; i++) {
				outBundle.putBoolean(GS_BUTTONENABLED + Integer.toString(i),
						SMBGuesstheNumber.arrisBtnNumberEnabled[i]);
			}
			for (i = 0; i < SMBGuesstheNumber.NBUTTON_STATE; i++) {
				outBundle.putInt(GS_BUTTONSTATES + Integer.toString(i),
						SMBGuesstheNumber.arrintBtnNumberStates[i]);
			}
			outBundle.putInt(GS_SECRETNUMBER, SMBGuesstheNumber.intSecretNumber);
		}
		return outBundle;
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState = savetheGameBundle(outState);
    }
*/
    
}